package org.handsomeking.mincroservice.hystrixDashboard.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/***
 * @author gaoqijin
 * @date 2021-3-12
 * @Description
 * 熔断测试案例
 */
@RestController
@RequestMapping("/hystrix/breaker")
public class CircuitBreakerController {


    @GetMapping
    public String index(){
        return "ok -- 嘻嘻~~";
    }

    @GetMapping("/timeout")
    @HystrixCommand(fallbackMethod = "fallbackTimeout",commandProperties = {
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),//是否打开熔断，默认true
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000"),//窗口期，默认5s
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),//出问题的阈值，默认50%
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "3")//请求数量阈值，默认20
    })
    public String timeout(String name){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "正常超时返回~~~";
    }

    @GetMapping("/error")
    @HystrixCommand(fallbackMethod = "fallbackError",commandProperties = {
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000"),//窗口期，默认5s
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),//出问题的阈值，默认50%
            @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "3")//请求数量阈值，默认20
    })
    public String error(String name){
        System.out.println(1/0);
        return "~";
    }
    public String fallbackTimeout(String name){
        return "超时啦~~~ ["+name+"] o(╥﹏╥)o";
    }
    public String fallbackError(String name){
        return "报错啦啦~~~ ["+name+"] o(╥﹏╥)o";
    }
}
